﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace RedFoxScraper
{
  public class ScraperService: IDisposable
  {
    Thread mThread;
    ConcurrentQueue<IJob> mQueue;

    public ScraperService()
    {
      mQueue = new ConcurrentQueue<IJob>();
      mThread = new Thread(run);
      mThread.Start();
    }

    public void run()
    {
      while (true)
      {
        if (mQueue.Count == 0)
        {
          Thread.Sleep(1000);
          continue;
        }
        IJob job;
        if (mQueue.TryDequeue(out job))
          job.perform();
      }
    }

    public void Dispose()
    {
      Debug.WriteLine("ScraperService is disposing...");
      mThread.Abort();
      // TODO: serialize queue.
    }

    public void addJob(IJob job)
    {
      mQueue.Enqueue(job);
    }
  }
}
